import pyaudio
import numpy as np
import random  # 导入random模块

def count_table_hits(audio_data, threshold):
    # 将音频数据转换为绝对值
    abs_audio_data = np.abs(audio_data)

    # 通过阈值判断是否存在敲击
    hits = (abs_audio_data > threshold).sum()

    return hits

def record_audio(fs, duration):
    audio = pyaudio.PyAudio()

    stream = audio.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=fs,
                        input=True,
                        frames_per_buffer=1024)

    frames = []
    for i in range(int(fs / 1024 * duration)):
        data = stream.read(1024)
        frames.append(data)

    stream.stop_stream()
    stream.close()
    audio.terminate()

    audio_data = np.frombuffer(b"".join(frames), dtype=np.int16)
    return audio_data

def play_game():
    print("欢迎来到剪刀石头布游戏！")

    fs = 44100  # 采样率
    duration = 1  # 录制时长（秒）
    threshold = 0.1  # 阈值，根据实际情况调整

    while True:
        # 录制音频
        recording = record_audio(fs, duration)

        # 计算敲击次数
        hits = count_table_hits(recording, threshold)

        # 判断用户选择
        if hits >= 3:
            user_choice = "剪刀"
        elif hits == 2:
            user_choice = "石头"
        else:
            user_choice = "布"

        # 打印选择结果和调试信息
        print(f"用户选择: {user_choice}")
        print(f"敲击次数（调试信息）: {hits}")

        # 模拟电脑选择
        computer_choice = random.choice(["剪刀", "石头", "布"])

        # 判断胜负
        if user_choice == computer_choice:
            print("结果: 平局")
        elif (user_choice == "剪刀" and computer_choice == "布") or (user_choice == "石头" and computer_choice == "剪刀") or (user_choice == "布" and computer_choice == "石头"):
            print("结果: 用户胜利")
        else:
            print("结果: 电脑胜利")

        # 询问是否再玩一局
        play_again = input("是否再玩一局？(按下回车键继续，输入其他内容退出): ")
        if play_again.lower() != "":
            break

play_game()
